const Fs = require('fs');
const Cp = require('child_process');
const Os = require('os');

const buildPath = './android/app/src/main/assets/apps/H56086A71/www';

async function deleteFile(path) {
  let files = [];

  if (Fs.existsSync(path)) {
    if (Fs.statSync(path).isDirectory()) {
      files = Fs.readdirSync(path);
      files.forEach((file) => {
        const curPath = `${path}/${file}`;

        if (Fs.statSync(curPath).isDirectory()) {
          deleteFile(curPath);
        } else {
          Fs.unlinkSync(curPath);
        }
      });
      Fs.rmdirSync(path);
    } else {
      Fs.unlinkSync(path);
    }
  }
}

async function copyFile(from, to) {
  let files = [];

  if (Fs.existsSync(to)) {
    files = Fs.readdirSync(from);
    files.forEach((file) => {
      const targetPath = `${from}/${file}`;
      const toPath = `${to}/${file}`;

      if (Fs.statSync(targetPath).isDirectory()) {
        copyFile(targetPath, toPath);
      } else {
        Fs.copyFileSync(targetPath, toPath);
      }
    });
  } else {
    Fs.mkdirSync(to);
    copyFile(from, to);
  }
}

async function buildVue() {
  return new Promise((resolve, reject) => {
    Cp.exec('vue-cli-service build', null, (err) => {
      if (!err) {
        console.log('\x1B[32m%s\x1B[0m', '编译完成');
        Fs.copyFileSync('./manifest.json', './dist/manifest.json');
        copyFile('./dist', buildPath);
        resolve('编译完成');
      } else {
        console.log('\x1B[31m%s\x1B[0m', `编译失败${err}`);
        reject(new Error(`编译失败${err}`));
      }
    });
  });
}

async function buildApk() {
  let command = '';

  if (Os.type() === 'Windows_NT') {
    command = 'cd android && gradlew clean && gradlew assembleRelease && cd ..';
  } else {
    command = 'cd android && ./gradlew clean && ./gradlew assembleRelease && cd ..';
  }

  return new Promise((resolve, reject) => {
    Cp.exec(command, null, (err) => {
      if (!err) {
        console.log('\x1B[32m%s\x1B[0m', 'apk打包完成');
        resolve('apk打包完成');
      } else {
        console.log('\x1B[31m%s\x1B[0m', `apk打包失败：${err}`);
        reject(new Error(`apk打包失败：${err}`));
      }
    });
  });
}

async function removeAssets() {
  return new Promise((resolve) => {
    if (Fs.existsSync(buildPath)) {
      deleteFile(buildPath);
      console.log('\x1B[32m%s\x1B[0m', '删除android app成功');
    }
    resolve('删除android app成功');
  });
}

async function init() {
  await removeAssets();
  await buildVue();
  await buildApk();
}

init();

process.on('unhandledRejection', (reason, promise) => {
  console.log('\x1B[31m%s\x1B[0m', '未处理的拒绝：', promise, '原因：', reason);
});
